package com.yuanhang.readsms;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.yuanhang.readsms.bean.Phone;
import com.yuanhang.readsms.databinding.ActivityAddNunberBinding;
import com.yuanhang.readsms.utils.TimeUtils;

import org.litepal.LitePal;

import java.util.List;

/**
 * 添加号码
 */
public class AddNumberActivity extends AppCompatActivity implements View.OnClickListener {

    private ActivityAddNunberBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityAddNunberBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        initView();
        initData();
    }

    private void initView() {
        binding.icTitle.tvTitle.setText("添加号码");
        binding.icTitle.ivBack.setOnClickListener(this);
        binding.btnSave.setOnClickListener(this);
    }

    private void initData() {

    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ivBack) {
            finish();
        } else if (id == R.id.btnSave) {
            if (!TextUtils.isEmpty(binding.etNumber.getText().toString().trim())) {
                List<Phone> allPhone = LitePal.findAll(Phone.class);
                for (int i = 0; i < allPhone.size(); i++) {
                    if (allPhone.get(i).getPhoneNum().equals(binding.etNumber.getText().toString().trim())) {
                        Toast.makeText(this, "该号码已添加，请不要重复添加", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }

                //保存号码和添加号码时间
                Phone phone = new Phone();
                phone.setPhoneNum(binding.etNumber.getText().toString().trim());
                phone.setAddPhoneNumTime(TimeUtils.dateToString(TimeUtils.getTimeStame()));
                phone.save();
                Toast.makeText(this, "号码添加成功", Toast.LENGTH_SHORT).show();
                setResult(Activity.RESULT_OK);
                finish();
            } else {
                Toast.makeText(this, "号码不能为空", Toast.LENGTH_SHORT).show();
            }
        }
    }
}